/**
 * create by Alec
 */

import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import autobind from "autobind-decorator";

// components
import DateRange from "../../components/DateRange";
import HelpModal from "../../components/HelpModal";

// submodule
import "./index.less";

// modules
import PersonnelChange from "./personnelChange";
import OnJobChart from "./onJobChart";
import PersonnelList from "./personnelList";
import DeptList from "./deptList";
import Breadcrumb from "./breadcrumb";
import ExpireDateView from "./expireDateView";
// utils
import monitor from "../../utils/monitor.js";
import { getUrlParam, type } from "../../utils/common.js";
import {
    setTitle,
    goBack,
    close,
    openLink,
    toast
} from "../../utils/dingtalk.js";

// actions
import { fetchPersonnelWeekly } from "../../actions/personnelWeekly/index.js";

// 将store注入组件的props
const mapStateToProps = state => ({
    weekly: { ...state.PERSONNELWEEKLY_REPORT }
});
// 将action与dispatch进行绑定并注入组件的props
const mapDispatchToProps = dispatch => ({
    //区分绑定到props的action与传递的props
    actions: bindActionCreators(
        {
            dispatch,
            fetchPersonnelWeekly
        },
        dispatch
    )
});

@connect(mapStateToProps, mapDispatchToProps)
export default class Pending extends Component {
    static defaultProps = {
        weekly: {}
    };
    //propTypes 验证
    static propTypes = {
        weekly: PropTypes.object.isRequired,
        actions: PropTypes.shape({
            dispatch: PropTypes.func.isRequired,
            fetchPersonnelWeekly: PropTypes.func.isRequired
        }).isRequired
    };
    constructor(props) {
        super(props);
        this.state = {
            weeklyData: {},
            currentDate: "",
            isLoading: true,
            navList: [],
            curPeriod: "week"
        };
        setTitle({
            title: "人事报表"
        });
    }
    componentWillUpdate() {
        
    }

    componentWillMount() {
        const currentDate = getUrlParam("time") || "";
        let param = {};
        if (this.props.location) {
            const { time = "", deptId = "", period = 'week' } = this.props.location.query || {};
            if (deptId) {
                param = {
                    time,
                    deptId,
                    periodType: period,
                };
            } else {
                param.time = currentDate;
            }
            this.setState({ currentDate: param.time, curPeriod: period });
        }
    
        //setTitle({ title: "人事统计" });
        this.setState({ currentDate: param.time });
        this.getPersonnelWeekly(param);
    }
    /** 获取周报数据
     *  后续改动允许获取以月为单位或者以周为单位获取数据
     *  添加字段period =>  week or month
    */
    @autobind
    // @monitor({})
    getPersonnelWeekly(param) {
        this.props.actions
        .fetchPersonnelWeekly(param)
        .then(res => {
            if (res.success) {
                const { result } = res;
                const nav = [{ deptName: "全公司", deptId: "all" }];
                const deptList = result.deptList || [];
                let curDate = this.state.curPeriod === 'week' ? result.currentTime.value : result.currentMonth.value
                this.setState({
                    weeklyData: result,
                    currentDate: curDate,
                    isLoading: false,
                    navList: nav.concat(deptList)
                });

                if (deptList.length > 1) {
                    const title = deptList[deptList.length - 1].deptName || "";
                    setTitle({
                        title: title,
                    });
                }
            }
        })
        .catch(error => {
            console.log(error);
        });
    }
    /**
     * 日期切换 左侧回调
     */
    @autobind
    preDateCallback(lastTime) {
        if (!lastTime) {
            toast({
                text: "没有数据"
            });
        } else {
            const { curPeriod } = this.state;
            const { deptId = "" } = this.props.location.query || {};
            const param = {
                periodType: curPeriod,
                time: lastTime,
                deptId
            };
            this.getPersonnelWeekly(param);
        }
    }
    /**
     * 日期切换 右侧回调
     */
    @autobind
    nextDateCallback(nextTime) {
        if (!nextTime) {
            toast({
                text: "不能查看未来的数据"
            });
        } else {
            const { curPeriod } = this.state;
            const { deptId = "" } = this.props.location.query || {};
            const param = {
                periodType: curPeriod,
                time: nextTime,
                deptId
            };
            this.getPersonnelWeekly(param);
        }
    }
    /**
     * 选择部门
     * @param {*所选部门} dept 
     */
    @autobind
    chooseDept(dept) {
        const { currentDate, curPeriod } = this.state;
        openLink(`#/personnelWeekly?time=${currentDate}&deptId=${dept.deptId}&period=${curPeriod}`);
    }
    /**
     * 面包屑菜单栏根据所选部门调取接口
     * @param {*部门ID} deptId 
     */
    @autobind
    handleNavList(deptId, index) {
        let { currentDate, navList, curPeriod } = this.state;
        console.log(navList);
        if (navList.length > 1 && deptId === navList.slice(-1)[0].deptId) {
            return;
        }
        if (deptId === "all") {
            openLink(`#/personnelWeekly?time=${currentDate}&period=${curPeriod}`);
        } else {
            openLink(`#/personnelWeekly?time=${currentDate}&}deptId=${deptId}&period=${curPeriod}`);
        }
    }

    /**
     * 时间间隔切换 月统计或者周统计
     */
    @autobind
    togglePeriod(period){
        const { curPeriod, weeklyData } = this.state;
        const { deptId = "" } = this.props.location.query || {};
        var time; 
        if(curPeriod === period){
            return;
        }
        console.log(weeklyData);
        if (period === 'week'){
            time = weeklyData.currentTime.value;
        } else {
            time = weeklyData.currentMonth.value;
        }
        const param = {
            time: time,
            deptId: deptId,
            periodType: period,
        }

        this.setState({
            curPeriod: period
        }, this.getPersonnelWeekly(param))
    }

    // /**
    //  * 取日期区间
    //  * @param {*时间Str} date
    //  */
    // @autobind
    // getRangeDate(date) {
    //     if(type(date) !== 'string') {
    //         return;
    //     }
    //     return date.split(' ').slice(-1).join('');
    // }
    /**
     * 拿到截止日期
     * @param {*时间Str} date 
     */
    @autobind
    getExpiryDate(date) {
        if (type(date) !== "string") {
            return;
        }
        return date.split("-").slice(-1).join("");
    }
    render() {
        const {
            totalEntry,
            totalDismission,
            totalTransfer,
            totalTransferIn,
            totalTransferOut,
            totalBeRegular,
            dimissionExplainVO,
            currentTime = {},
            lastTime,
            nextTime,
            currentMonth = {},
            lastMonth,
            nextMonth,
            totalEmployee = 0,
            weeklyDeptVOList,
            totalFullTime,
            totalPartTime,
            totalInternShip,
            totalOther,
            totalRegular,
            totalProbationary,
            totalPendingDismission,
            weeklyStatisticVOList,
            weeklyDismissionList,
            weeklyEntryList,
        } = this.state.weeklyData || {};
        const { navList, currentDate, isLoading, curPeriod } = this.state || {};
        const status = {
            totalFullTime,
            totalPartTime,
            totalInternShip,
            totalOther
        };
        const type = { totalRegular, totalProbationary, totalPendingDismission };
        const expiryDateRange = this.state.curPeriod === 'week' ? currentTime.displayValue : currentMonth.displayValue;
        const expiryDate = this.getExpiryDate( this.state.curPeriod === 'week' ? currentTime.displayValue : currentMonth.displayValue);
        const count = { dimissionExplainVO, expiryDateRange };
        const changeList = [
            { value: totalEntry, label: "entry" },
            { value: totalDismission, label: "dimission" },
            { value: totalTransferIn, label: "transferIn" },
            { value: totalTransferOut, label: "transferOut" },
            { value: totalTransfer, label: "totalTransfer" },
            { value: totalBeRegular, label: "totalBeRegular" },
        ];
        const onJob = { totalEmployee, expiryDate, weeklyStatisticVOList, weeklyDismissionList, weeklyEntryList };
        const query = this.props.location.query || {};
        const urlParam = { currentDate, query };
        console.log(urlParam)
        const deptShow = navList.length > 1 ? 0 : 30;
        const curPeriodBool = this.state.curPeriod === 'week' ? true : false;
        navList.length > 1 && setTitle({ title: navList[navList.length - 1].deptName  });
        return (
            <div className="personnel-weekly-container">
                {
                    !isLoading && 
                    <DateRange
                        lastTime={ curPeriodBool ? lastTime : lastMonth }
                        nextTime={ curPeriodBool ? nextTime : nextMonth }
                        currentTime={ curPeriodBool ? currentTime : currentMonth }
                        totalEmployee={totalEmployee}
                        onLeftClick={this.preDateCallback}
                        onRightClick={this.nextDateCallback}
                        period={curPeriod}
                        togglePeriod={this.togglePeriod}
                    />
                }
                <div className={`personnel-weekly ${navList.length > 1 && 'check-dept'}`}>
                {
                    !isLoading ? 
                    <div ref="deptScroll">
                        {
                            totalEmployee > 0 ? 
                            <div className="weekly">
                                {
                                    navList.length > 1 && 
                                    <Breadcrumb
                                        navList={navList}
                                        handleNavList={this.handleNavList}
                                    />
                                }

                                <PersonnelChange
                                    count={count}
                                    period={curPeriod}
                                    urlParam={urlParam}
                                    changeList={changeList}
                                />

                                <OnJobChart 
                                    onJob={onJob}
                                    period={curPeriod} />

                                <ExpireDateView
                                    deptList={weeklyDeptVOList}
                                    expiryDate={expiryDate}
                                    />

                                <PersonnelList
                                    data={status}
                                    period={curPeriod}
                                    title={"员工类型"}
                                    color={"orange"}
                                    urlParam={urlParam}
                                />

                                <PersonnelList
                                    data={type}
                                    period={curPeriod}
                                    title={"员工状态"}
                                    color={"green"}
                                    urlParam={urlParam}
                                />

                                <DeptList
                                    deptList={weeklyDeptVOList}
                                    expiryDate={expiryDate}
                                    chooseDept={this.chooseDept}
                                />
                                
                            </div> : 
                            <div className="totalEmployee-empty">
                                <img src="https://img.alicdn.com/tfs/TB1YGyrhfBNTKJjy0FdXXcPpVXa-216-186.png"
                                    alt="暂无数据"
                                />
                                <p>暂无数据</p>
                            </div>
                        }
                    </div> : 
                    <div></div>
                }
                </div>
                <HelpModal/>
            </div>
        );
    }
}